import axios from "axios";

import { BASE_URL, TIMEOUT } from "./config";

import localCache from "./cache";

class Request {
  constructor() {
    this.instance = axios.create({
      baseURL: BASE_URL,
      timeout: TIMEOUT,
    });

    this.instance.interceptors.request.use(
      (config) => {
        const token = localCache.getCache("token");
        if (config && token) {
          config.headers.Authorization = `Bearer ${token}`;
        }

        return config;
      },
      (err) => {
        return err;
      }
    );

    this.instance.interceptors.response.use(
      (res) => {
        const { data, status } = res;
        if (status === 200) return data.data;
      },
      (err) => {
        const { status, data } = err.response;
        switch (status) {
          case 401:
            // 未授权，跳转到登录页
            ElMessage.error("未授权，请重新登录");
            // localStorage.removeItem("token");
            window.location.href = "/login";
            break;
          case 403:
            ElMessage.error("拒绝访问");
            break;
          case 404:
            ElMessage.error("请求资源不存在");
            break;
          case 500:
            ElMessage.error("服务器内部错误");
            break;
          default:
            ElMessage.error(data.message || `连接错误${status}`);
        }
        return err;
      }
    );
  }

  request(config) {
    return new Promise((resolve, rejects) => {
      this.instance
        .request(config)
        .then((res) => {
          resolve(res);
        })
        .catch((err) => {
          rejects(err);
        });
    });
  }
  get(config) {
    return this.request({ ...config, method: "GET" });
  }
  post(config) {
    return this.request({ ...config, method: "POST" });
  }
  delete(config) {
    return this.request({ ...config, method: "DELETE" });
  }
  patch(config) {
    return this.request({ ...config, method: "PATCH" });
  }
}

const R = new Request();
export default R;
